package com.wangsd.web.report.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.binarywang.wxpay.bean.request.WxPayDownloadBillRequest;
import com.github.binarywang.wxpay.bean.result.WxPayBillInfo;
import com.github.binarywang.wxpay.bean.result.WxPayBillResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.wangsd.common.component.WeixinPayService;
import com.wangsd.common.utils.DateUtils;
import com.wangsd.web.report.entity.BillRecord;
import com.wangsd.web.report.entity.Manufacturer;
import com.wangsd.web.report.entity.Merchant;
import com.wangsd.web.report.entity.ServiceBusiness;
import com.wangsd.web.report.mapper.BillRecordMapper;
import com.wangsd.web.report.service.BillRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wangsd.web.report.service.ManufacturerService;
import com.wangsd.web.report.service.MerchantService;
import com.wangsd.web.report.service.ServiceBusinessService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author generator
 * @since 2019-10-15
 */
@Service
public class BillRecordServiceImpl extends ServiceImpl<BillRecordMapper, BillRecord> implements BillRecordService {

    @Resource
    BillRecordMapper billRecordMapper;
    @Autowired
    WeixinPayService weixinPayService;
    @Autowired
    ManufacturerService manufacturerService;
    @Autowired
    ServiceBusinessService serviceBusinessService;
    @Autowired
    MerchantService merchantService;

    @Override
    public void downloadWxBill() {
        //查询所有厂商
        List<Manufacturer> list = manufacturerService.selectAll();
        if (list != null) {
            //查询所有服务商
            for (Manufacturer manufacturer : list) {
                List<ServiceBusiness> businessList = serviceBusinessService.selectByManufacturerId(manufacturer.getId());
                if (businessList != null) {
                    for (ServiceBusiness business : businessList) {
                        List<Merchant> merchantList = merchantService.selectByBusinessId(business.getId());
                        if (merchantList != null) {
                            for (Merchant merchant : merchantList) {
                                //下载服务商对账单
                                WxPayService wxPayService = weixinPayService.getService(business.getId(), merchant.getSubMchId());
                                WxPayDownloadBillRequest request = new WxPayDownloadBillRequest();
                                request.setBillDate(DateUtils.getNDayBeforDate(1, "yyyyMMdd"));
                                request.setBillType("SUCCESS");
                                try {
                                    WxPayBillResult result = wxPayService.downloadBill(request);
                                    //获取查询结果
                                    if (result != null && result.getBillInfoList() != null) {
                                        //保存对账单
                                        for (WxPayBillInfo bill : result.getBillInfoList()) {
                                            try {
                                                BillRecord billRecord = new BillRecord();
                                                BeanUtils.copyProperties(bill, billRecord);
                                                billRecord.setReportStatus(0);
                                                billRecordMapper.insert(billRecord);
                                            } catch (Exception e) {
                                                continue;
                                            }
                                        }
                                    }
                                } catch (WxPayException e) {
                                    log.error(merchant.getName() + "-" + merchant.getSubMchId() + "下载对账单失败！");
                                    continue;
                                }

                            }
                        }
                    }
                }
            }
        }

    }

    @Override
    @Transactional
    public List<BillRecord> selectBySubMckIdAndStaus(String mchId, int status) throws Exception {
        Merchant merchant = merchantService.selectBySubMchId(mchId);
        if (merchant == null) {
            throw new Exception("商户信息异常");
        }
        ServiceBusiness business = serviceBusinessService.getById(merchant.getServiceBusinessId());
        if (business == null) {
            throw new Exception("服务商信息异常");
        }
        ///只要服务商余额大于0,执行完当前这次上报
        if (business.getTotalFee() <= 0) {
            throw new Exception("服务商账户余额不足！");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("sub_mch_id", mchId);
        queryWrapper.eq("report_status", status);
        //所有需要上报的数据
        List<BillRecord> list = billRecordMapper.selectList(queryWrapper);
        //拿到当前上报的总金额
        Double totalAmount = billRecordMapper.selectTotalFee(mchId, status);

        //上报数据大于0，上报金额大于0
        if (list.size() > 0 && totalAmount != null && totalAmount > 0) {
            Double d = totalAmount * business.getReportRate();
            Double fee = Double.valueOf(String.format("%.2f", d));
            if (fee < 0.01) {//交易上报最低扣除0.01
                fee = 0.01;
            }
            //修改服务商余额
            business.setTotalFee(business.getTotalFee() - fee);
            serviceBusinessService.addOrUpdate(business);

            //修改当前数据为已上报
            billRecordMapper.updateStatusBySubMchId(mchId);
        }
        return list;
    }
}
